package com.xintool.window.Buttons;

import javazoom.jl.player.Player;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Deprecated
public class Button_timer extends ButtonFactory {


    private static JFrame frame;
    private JLabel timeLabel;
    private JComboBox<Integer> timeCombo;
    private JComboBox<String> soundCombo;
    private Timer countdownTimer;
    private int initialSeconds;

    private static final String MUSIC_DIR = "music"; // 存放音乐的目录名

    // 在类中添加以下字段
    private volatile boolean isSoundTriggered = false;

    @Override
    public JButton showButton() {
        JButton button = ButtonFactory.getButton("计时器");
        button.addActionListener(e -> createMainWindow());
        return button;
    }

    private void createMainWindow() {
        if (frame != null && frame.isDisplayable()) {
            frame.toFront();
            return;
        }

        frame = new JFrame("计时器");
        frame.setSize(400, 200);
        frame.setLayout(new GridBagLayout());
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 时间显示
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        timeLabel = new JLabel("15", SwingConstants.CENTER);
        timeLabel.setFont(new Font("Arial", Font.BOLD, 36));
        frame.add(timeLabel, gbc);

        // 时间选择
        gbc.gridy = 1;
        gbc.gridwidth = 1;
        JPanel timePanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
        timePanel.add(new JLabel("时长:"));
        timeCombo = new JComboBox<>(new Integer[]{5, 8, 10, 12, 13, 14, 15, 20, 30, 45, 60});
        timeCombo.setPreferredSize(new Dimension(60, 25));
        timeCombo.setSelectedItem(15);
        timePanel.add(timeCombo);
        frame.add(timePanel, gbc);

        // 铃声选择
        gbc.gridx = 1;
        JPanel soundPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 0));
        soundCombo = new JComboBox<>(scanMusicDirectory().toArray(new String[0]));
        soundCombo.setPreferredSize(new Dimension(100, 25));
        JButton playButton = new JButton("▶");
        //playButton.setPreferredSize(new Dimension(30, 25));
        playButton.addActionListener(e -> playSelectedSound());
        soundPanel.add(new JLabel("铃声:"));
        soundPanel.add(soundCombo);
        soundPanel.add(playButton);
        frame.add(soundPanel, gbc);

        // 开始按钮
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        JButton startButton = new JButton("开始");
        startButton.addActionListener(e -> startCountdown());
        frame.add(startButton, gbc);

        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                stopTimer();
            }
        });

        frame.setVisible(true);
    }

    // 动态扫描音乐目录的方法
    private List<String> scanMusicDirectory() {
        List<String> soundFiles = new ArrayList<>();
        File musicDir = new File(MUSIC_DIR);

        // 如果目录不存在则创建
        if (!musicDir.exists()) {
            musicDir.mkdir();
        }

        File[] files = musicDir.listFiles((dir, name) ->
                name.toLowerCase().endsWith(".mp3")
        );

        if (files != null) {
            for (File f : files) {
                soundFiles.add(f.getName());
            }
        }
        return soundFiles;
    }

    private void startCountdown() {
        stopTimer();
        initialSeconds = (Integer) timeCombo.getSelectedItem()+1;
        timeLabel.setText(String.valueOf(initialSeconds));
        isSoundTriggered = false; // 重置声音触发标志

        countdownTimer = new Timer(1000, e -> {
            int remaining = Integer.parseInt(timeLabel.getText());
            // 当剩余时间 ≤ 0.5秒时触发声音（仅触发一次）
            if (remaining == 1 && !isSoundTriggered) {
                playSelectedSound(); // 触发播放
                isSoundTriggered = true;
            }

            // 正常倒计时逻辑
            remaining--;
            timeLabel.setText(String.valueOf(remaining));

            if (remaining < 0) {
                countdownTimer.stop(); // 停止计时器
                resetTimer();          // 重置时间
                startCountdown();      // 重新开始循环
            }
        });

        // 设置首次延迟以对齐剩余时间（关键！）
        countdownTimer.setInitialDelay(0);
        countdownTimer.start();
    }

    private void resetTimer() {
        timeLabel.setText(String.valueOf(initialSeconds));
    }

    private void stopTimer() {
        if (countdownTimer != null && countdownTimer.isRunning()) {
            countdownTimer.stop();
        }
    }

    private void playSelectedSound() {
        String selected = (String) soundCombo.getSelectedItem();
        if (selected == null || selected.isEmpty()) {
            SwingUtilities.invokeLater(() ->
                    JOptionPane.showMessageDialog(frame, "请选择有效的提示音")
            );
            return;
        }

        new Thread(() -> {
            try (InputStream is = new FileInputStream(new File(MUSIC_DIR, selected))) {
                Player player = new Player(is);
                player.play();
            } catch (Exception e) {
                SwingUtilities.invokeLater(() ->
                        JOptionPane.showMessageDialog(frame, "播放失败: " + e.getMessage())
                );
            }
        }).start();
    }
}